/*
 * @Date: 2025-08-25 15:17:37
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-10-05 15:33:14
 * @FilePath: \corpus\src\components\Category\index.tsx
 */
import { getDeptList } from '@/services/ant-design-pro/dept';
import { useModel } from '@umijs/max';
import { Input, message, Spin, Tree } from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useState } from 'react';

const { Search } = Input;

import styles from './index.less';
const Category = (props: { height: any }) => {
  const { setName, actionRef, selectedKeys, setSelectedKeys } = useModel('useTree', (model) => {
    return {
      setName: model.setName,
      selectedKeys: model.selectedKeys,
      setSelectedKeys: model.setSelectedKeys,
      name: model.name,
      actionRef: model.actionRef,
    };
  });
  interface TreeNode extends DataNode {
    id: string;
    type?: 'department' | 'employee';
  }

  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadedKeys, setLoadedKeys] = useState<React.Key[]>([]);

  // 初始化加载根节点

  const fetchNodes = async (value: string, parentOrganizationCode: string) => {
    setLoading(true);
    try {
      const res = await getDeptList(
        parentOrganizationCode !== '0'
          ? { parentOrganizationCode: parentOrganizationCode }
          : {
              searchValue: value,
            },
      );

      const formattedData = res.data.map((item: any) => ({
        id: item.organizationCode,
        key: item.organizationCode,
        title: item.govShortName,
        isLeaf: item.orgType === 'GOV_UNIT',
      }));

      if (parentOrganizationCode === '0') {
        setTreeData(formattedData);
      } else {
        setTreeData((origin) => updateTreeData(origin, parentOrganizationCode, formattedData));
        setLoadedKeys((prev) => [...prev, parentOrganizationCode]);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchNodes('', '0');
  }, []);
  const updateTreeData = (list: TreeNode[], key: React.Key, children: TreeNode[]): TreeNode[] => {
    return list.map((node) => {
      if (node.key === key) {
        return { ...node, children };
      }
      if (node.children) {
        return { ...node, children: updateTreeData(node.children, key, children) };
      }
      return node;
    });
  };

  const onLoadData = async ({ key, children }: any) => {
    if (children || loadedKeys.includes(key)) return;
    console.log(key);
    await fetchNodes('', key.toString());
  };

  return (
    <>
      <div className={styles.content}>
        <Search
          placeholder="请输入"
          onSearch={(arg: string) => {
            console.log(arg);
            fetchNodes(arg, '0');
          }}
          style={{ width: '100%', padding: '16.0px 10.0px 10.0px 10.0px' }}
        />

        <ul
          style={{ height: props.height ? props.height - 70 + 'px' : '' }}
          className={props.height ? styles.typeContent : styles.treeContent}
        >
          <Spin spinning={loading}>
            <Tree
              loadData={onLoadData}
              treeData={treeData}
              selectedKeys={selectedKeys}
              fieldNames={{ title: 'title', key: 'key', children: 'children' }}
              onSelect={(
                selectedKeys: any,
                e: { selected: boolean; selectedNodes: any; node: any; event: any },
              ) => {
                if (e.node.isLeaf) {
                  setSelectedKeys(selectedKeys);

                  if (e.selected) {
                    console.log(e);
                    setName(e.node.title);
                    actionRef.current?.reload();
                  } else {
                    setName('');
                    actionRef.current?.reload();
                  }
                } else {
                  message.error('请选择二级部门');
                }
              }}
            />
          </Spin>
        </ul>
      </div>
    </>
  );
};

export default Category;
